package com.xiaolei.fastnio.http.Comm

import com.xiaolei.fastnio.http.requestBodyFileDir
import com.xiaolei.fastnio.library.Client.Session
import com.xiaolei.fastnio.library.Protocol.Cleanable
import java.io.File
import java.io.RandomAccessFile
import java.util.*

/**
 * 请求体转换成字节数组，存到文件里
 */
class RequestBodyFile : Cleanable
{
    var session: Session? = null
        set(value)
        {
            bodyFile.seek(0)
            bodyFile.setLength(0)
            field = value
        }
    private val bodyFile = RandomAccessFile(File(requestBodyFileDir, UUID.randomUUID().toString()), "rw")

    /**
     * 获取长度
     */
    val size get() = bodyFile.length()

    /**
     * 覆盖写入
     */
    fun write(bytes: ByteArray, offset: Int, len: Int)
    {
        bodyFile.seek(0)
        bodyFile.write(bytes, offset, len)
    }

    /**
     * 追加写入
     */
    fun append(bytes: ByteArray, offset: Int, len: Int)
    {
        bodyFile.seek(bodyFile.length())
        bodyFile.write(bytes, offset, len)
    }


    override fun onClear()
    {
        bodyFile.seek(0)
        bodyFile.setLength(0)
        session = null
    }
}